from django.shortcuts import render
from django.shortcuts import redirect
from .models import Register, Poem  # 导入模型
import logging
from django.http import HttpResponse,HttpResponseRedirect
from .import service
from rest_framework import serializers
from rest_framework.validators import UniqueValidator

logger = logging.getLogger(__name__)

# Create your views here.


def index(request):
    poems = service.getAllPoems()  # 查询所有诗歌
    return render(request, 'index.html', {'poems': poems})  # 将诗歌传递给模板

#针对模型设计序列化器
class RegisterSerializer(serializers.ModelSerializer):
    username = serializers.CharField(
        max_length=20,
        validators=[UniqueValidator(queryset=Register.objects.all())]
    )
    onepassword = serializers.CharField(max_length=20)
    twopassword = serializers.CharField(max_length=20, default='defaultpassword')
    email = serializers.EmailField(
        validators=[UniqueValidator(queryset=Register.objects.all())]
    )
    phone = serializers.CharField(
        max_length=15,
        validators=[UniqueValidator(queryset=Register.objects.all())]
    )

    class Meta:
        model = Register
        fields = ['username', 'onepassword', 'twopassword', 'email', 'phone']


def register(request):
    logger.info("Register view called")
    if request.method == 'POST':

        # 构建序列化器对象
        serializer = RegisterSerializer(data=request.POST)

        # 验证数据
        if serializer.is_valid():
            # 如果数据有效，可以保存到数据库
            serializer.save()
            return redirect('login')  # 注册成功后重定向到登录页面
        else:
            # 如果数据无效，返回错误信息
            return render(request, 'register.html', {'error_msg': serializer.errors})
    else:
        return render(request, 'register.html')
    
def login(request):
    logger.info("Login view called")
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        # 验证用户名和密码是否匹配
        try:
            user = Register.objects.get(username=username, onepassword=password)
            if user:
                logger.info(f"User {username} logged in successfully")
                request.session['username'] = username  # 保存用户会话
            else:
                return render(request, 'login.html', {'error_msg': '用户名或密码错误！'})
        except Register.DoesNotExist:
            return render(request, 'login.html', {'error_msg': '用户名或密码错误！'})
        # 如果登录成功，重定向到 index 页面
        return redirect('index')
    else:
        return render(request, 'login.html')
    
def add(request): 
    return render(request,'add.html')

def svc_add(request):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        # 保存诗歌到数据库
        try:
            Poem.objects.create(
                title=title,
                content=content
            )
            return redirect('index')  # 添加成功后重定向到 index 页面
        except Exception as e:
            return render(request, 'add.html', {'error_msg': f'添加失败: {str(e)}'})
    else:
        return render(request, 'add.html')


def delete(request, id):
    try:
        poem = Poem.objects.get(id=id)
        poem.delete()
        return redirect('index')  # 删除成功后重定向到 index 页面
    except Poem.DoesNotExist:
        return HttpResponse("诗歌不存在")

def edit(request, id):
    poem = Poem.objects.get(id=id)
    return render(request, 'edit.html', {'poem': poem})

def svc_edit(request, id):
    if request.method == 'POST':
        title = request.POST.get('title')
        content = request.POST.get('content')
        # 更新诗歌到数据库
        try:
            poem = Poem.objects.get(id=id)
            poem.title = title
            poem.content = content
            poem.save()
            return redirect('index')  # 更新成功后重定向到 index 页面
        except Exception as e:
            return render(request, 'edit.html', {'error_msg': f'更新失败: {str(e)}'})
    else:
        return render(request, 'edit.html')
